<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogVisible"
    :append-to-body="true"
    :close-on-click-modal="false"
    @close="handleColse"
    width="40%">
    <el-form
      :model="dataForm"
      :rules="dataFormRules"
      ref="dataForm"
      size="small"
      label-width="80px">
      <el-form-item
        label="名称"
        prop="roleName">
        <el-input
          v-model="dataForm.roleName"
          placeholder="请输入名称"
          :clearable="true"/>
      </el-form-item>

      <el-form-item
        label="描述"
        prop="description">
        <el-input
          v-model="dataForm.description"
          placeholder="可输入描述"
          type="textarea"
          :rows="5"/>
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item
            label="排序值"
            prop="sort">
            <el-input-number
              v-model="dataForm.sort"
              controls-position="right"
              :min="0"
              :max="255"
              style="width: 120px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="状态"
            prop="status">
            <el-switch
              v-model="dataForm.status"
              active-value="0"
              inactive-value="1">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item
            label="菜单权限"
            prop="menuIds">
            <el-tree
              node-key="id"
              :data="menuData"
              :props="defaultProps"
              :show-checkbox="true"
              ref="menuTree">
                <span class="custom-tree-node" slot-scope="{node, data}">
                  <span class="brother-showing" :class="{'status-tree': !data.status}">
                    <i v-if="data.icon" :class="`iconfont icon${data.icon}`"/>
                    <i v-else-if="data.children" :class="`el-icon-${node.expanded ? 'folder-opened' : 'folder'}`"/>
                    <i v-else class="el-icon-document"/>
                    {{node.label}}
                    <i v-if="data.url" class="el-icon-link">
                      {{data.url}}
                    </i>
                  </span>
                </span>
            </el-tree>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="部门权限"
            prop="menuIds">
            <el-tree
              node-key="id"
              :data="deptData"
              :props="deptTreeProps"
              :show-checkbox="true"
              ref="deptTree">
                <span class="custom-tree-node" slot-scope="{node, data}">
                  <span class="brother-showing" :class="{'status-tree': !data.status}">
                    <i v-if="data.icon" :class="`iconfont icon${data.icon}`"/>
                    <i v-else-if="data.children" :class="`el-icon-${node.expanded ? 'folder-opened' : 'folder'}`"/>
                    <i v-else class="el-icon-document"/>
                    {{node.label}}
                    <i v-if="data.url" class="el-icon-link">
                      {{data.url}}
                    </i>
                  </span>
                </span>
            </el-tree>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button
        @click="handleColse"
        size="small">取消</el-button>

      <el-button
        v-if="dialogStatus === 'create'"
        type="primary"
        :loading="dialogLoading"
        @click="submitForm"
        size="small">确定</el-button>

      <el-button
        v-else type="primary"
        :loading="dialogLoading"
        @click="submitForm"
        size="small">修改</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getMenu } from '@/api/auth/menu'
import { getTreeDept } from '@/api/auth/user'
import { getAuthGroupItem, addAuthGroupItem } from '@/api/auth/group'
export default {
  props: {

  },
  data() {
    return {
			deptData: [],
      menuData: [],
      dialogVisible: false, // 新增编辑界面是否显示
      dialogLoading: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户组',
        create: '新增用户组'
      },
			// 新增编辑界面数据
			dataForm: {
				id: '',
				roleName: '',
				description: '',
        menuIds: [],
        deptList: [],
        sort: '0',
        status: '0'
      },
      dataFormRules: {
				roleName: [
					{ required: true, message: '请输入角色名', trigger: 'blur' }
				]
      },
      defaultProps: {
				children: 'children',
				label: 'menuTitle'
			},
			deptTreeProps: {
				label: 'simpleName',
				children: 'children'
			}
    }
  },
  created() {

  },
  methods: {
    // 对话框初始化
    init(status, params) {
      // 加载菜单及部门数据
      this.findTreeData()
      this.findDeptTree()
      this.dialogStatus = status
      // 清空表单
      this.clearForm()
      if (JSON.stringify(params) !== '{}') { // 修改
        // 获取单条数据
        getAuthGroupItem(params.roleId).then((res) => {
          if (res.code === 200) {
            // 打开对话框
            this.dialogVisible = true
            // 状态处理
            res.data.role.status = res.data.role.status ? res.data.role.status.toString() : '0'
            this.dataForm = res.data.role
            // 菜单数据处理
            this.dataForm.menuIds = res.data.menu.map(item => {
              return item.id
            })
            // 部门数据处理
            this.dataForm.deptList = res.data.dept.map(item => {
              return item.deptId
            })
            let that = this
            // 树形数据回显
            setTimeout(function () {
              that.dataForm.menuIds.forEach(value => {
                that.$refs.menuTree.setChecked(value, true, false)
              })
              that.dataForm.deptList.forEach(value => {
                that.$refs.deptTree.setChecked(value, true, false)
              })
            }, 500)
          }
        })
      } else {
        // 打开对话框
        this.dialogVisible = true
      }
    },
    // 获取菜单数据
		findTreeData: function () {
			getMenu().then((res) => {
        if (res.code === 200) this.menuData = res.data
			})
		},
		// 获取部门列表
		findDeptTree: function () {
			getTreeDept().then((res) => {
        if (res.code === 200) this.deptData = res.data
			})
    },
    // 清空表单
    clearForm() {
      for (let item in this.dataForm) {
        this.dataForm[item] = ''
        if (item === 'sort') {
          this.dataForm[item] = 0
        } else if (item === 'status') {
          this.dataForm[item] = '0'
        } else if (item === 'menuIds' || item === 'deptList') {
          this.dataForm[item] = []
        }
      }
    },
    // 获取勾选节点
    _getCheckedKeys() {
      this.dataForm.menuIds = [
        ...this.$refs.menuTree.getCheckedKeys(),
        ...this.$refs.menuTree.getHalfCheckedKeys()
			]
			this.dataForm.deptList = [
				...this.$refs.deptTree.getCheckedKeys(),
				...this.$refs.deptTree.getHalfCheckedKeys()
			]
    },
    // 提交数据
		submitForm(type) {
      // 验证表单
			this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
            // 获取勾选树的数据
            this._getCheckedKeys()
						let params = Object.assign({}, this.dataForm)
            params.id = params.roleId
            // 调用提交方法
						addAuthGroupItem(params).then((res) => {
							if(res.code == 200) {
                this.dialogVisible = false
                // 调用父级刷新列表方法
                this.$emit('refreshTable')
							} 
						})
					}).catch(() => {})
				}
			})
		},
    // 关闭弹框后后重置表单
    handleColse() {
      this.dialogVisible = false
      this.clearForm()
    }
  }
}
</script>